from flask import Flask, request, jsonify
import hmac
import hashlib
import base64
import json
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import os

app = Flask(__name__)

# 配置信息 - 请根据实际情况修改
CONFIG = {
#    'gitee_token': os.getenv('GITEE_WEBHOOK_TOKEN', '123456'),  # 与Gitee Webhook中设置的密码一致
    'smtp_server': 'smtp.163.com',  # 发件SMTP服务器
    'smtp_port': 465,              # SMTP端口（SSL一般为465）
    'from_email': 'liuhanxu163@163.com',  # 发件邮箱
    'from_pwd': 'XUbnj6pMQe78gyuC',  # 发件邮箱的授权码，非密码
    'to_email': [
        #'liupaopao520@163.com',  # 收件人邮箱
        '815085852@qq.com',  # 收件人邮箱
    ]
}

## 验证Gitee Webhook签名
#def verify_signature(timestamp, signature, data):
#    key = CONFIG['gitee_token'].encode('utf-8')
#    message = f"{timestamp}\n{key}".encode('utf-8')
#    # 注意：Gitee使用的是 hmac_sha256 算法:cite[6]
#    computed_signature = base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode('utf-8')
#    # 使用hmac.compare_digest防止时序攻击
#    return hmac.compare_digest(computed_signature, signature)

# 发送邮件的函数
def send_email(subject, content):
    # 将收件人列表转换为逗号分隔的字符串用于邮件头
    to_emails_str = ', '.join(CONFIG['to_email'])

    msg = MIMEText(content, 'html', 'utf-8')
    msg['From'] = Header(CONFIG['from_email'])
    #msg['To'] = Header(CONFIG['to_email'])
    msg['To'] = Header(to_emails_str)  # 在邮件头中显示所有收件人
    msg['Subject'] = Header(subject, 'utf-8')

    try:
        smtp = smtplib.SMTP_SSL(CONFIG['smtp_server'], CONFIG['smtp_port'])
        smtp.login(CONFIG['from_email'], CONFIG['from_pwd'])
        #smtp.sendmail(CONFIG['from_email'], [CONFIG['to_email']], msg.as_string())
        # 这里将收件人列表直接传递给sendmail
        smtp.sendmail(CONFIG['from_email'], CONFIG['to_email'], msg.as_string())
        smtp.quit()
        print("邮件发送成功")
        return True
    except Exception as e:
        print(f"邮件发送失败: {e}")
        return False

# 构建邮件内容的函数 (根据Push事件)
def build_email_content(data):
    # 解析Webhook JSON数据:cite[5]
    repo_name = data['repository']['name']
    committer = data['commits'][0]['author']['name'] if data['commits'] else data['pusher']['name']
    commit_time = data['commits'][0]['author']['time'] if data['commits'] else "No commit time info"
    commit_message = data['commits'][0]['message'] if data['commits'] else "No commit message"
    commit_num = data['total_commits_count'] if data['total_commits_count'] else "No commit count"
    commit_url = data['commits'][0]['url'] if data['commits'] else data['repository']['url']
    branch = data['ref'].split('/')[-1]  # 例如 'refs/heads/main' 提取 'main'

    subject = f"【{repo_name}】有新提交(by {committer})"

    content = f"""
    <html>
    <body>
        <h3>提交者  : {committer}</h3>
        <h3>分支    : {branch}</h3>
        <h3>提交信息: {commit_message}</h3>
        <h3>提交时间: {commit_time}</h3>
        <h3>提交数目: {commit_num}</h3>
        <h3>提交详情: <a href="{commit_url}">点击commits查看提交</a></h3>
    </body>
    </html>
    """
    return subject, content

@app.route('/webhook', methods=['POST'])
def handle_webhook():
    # 1. 获取Gitee的签名头和时间戳:cite[6]
    signature = request.headers.get('X-Gitee-Token', '')
    timestamp = request.headers.get('X-Gitee-Timestamp', '')

#    # 2. 验证签名（如果设置了密码）
#    if CONFIG['gitee_token']:
#        if not verify_signature(timestamp, signature, request.get_data()):
#            return jsonify({'status': 'error', 'message': 'Signature verification failed'}), 403

    # 3. 解析JSON数据
    try:
        data = request.get_json()
        event = request.headers.get('X-Gitee-Event', '')  # 获取事件类型，如 Push
    except Exception as e:
        return jsonify({'status': 'error', 'message': 'Invalid JSON'}), 400

    # 4. 根据事件类型处理（这里以Push事件为例）
    if event == 'Push' or event == 'push_hooks' or event == 'Push Hook':
        subject, email_content = build_email_content(data)
        # 5. 发送邮件
        if send_email(subject, email_content):
            return jsonify({'status': 'success', 'message': 'Email sent'}), 200
        else:
            return jsonify({'status': 'error', 'message': 'Failed to send email'}), 500

    # 可以扩展处理其他事件...
    else:
        return jsonify({'status': 'ignored', 'message': f'Event {event} not handled'}), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False)  # 生产环境请将debug设为False
